package com.terry.activity.controller.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.terry.activity.bean.BaseModel;
import com.terry.activity.bean.constant.ErrorCode;
import com.terry.activity.bean.exception.WechatAuthException;
import com.terry.activity.bean.message.ResponseMsg;
import com.terry.activity.bean.message.ResponseMsgData;
import com.terry.activity.bean.message.ResponseMsgJson;
import com.terry.activity.bean.message.ResponseMsgJsonArray;
import org.apache.log4j.Logger;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Create On 18/4/19.
 *
 * @author TerrySolar
 */
public abstract class BaseController {

    protected final Logger logger = Logger.getLogger(this.getClass());

    protected static String OPEN_ID = null;

    public BaseController() {

    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {

        new CustomWebDataBinder(binder);
    }


    /**
     * 检测是否微信授权，否则抛出异常
     *
     * @param request HttpServletRequest
     * @throws WechatAuthException
     */
    protected void assertWechatAuth(HttpServletRequest request) throws WechatAuthException {

        if (request.getSession().getAttribute("openid") == null) {
            throw new WechatAuthException();
        } else {
            OPEN_ID = request.getSession().getAttribute("openid").toString();
        }

    }


    protected ResponseMsg responseOK() {
        return new ResponseMsg(ErrorCode.OK, "OK");
    }

    protected ResponseMsg responseError(Integer errorCode, String msg) {
        return new ResponseMsg(errorCode, msg);
    }

    protected ResponseMsg responseJson(JSONObject data) {
        return new ResponseMsgJson(ErrorCode.OK, "OK", data);
    }

    protected ResponseMsg responseJsonArray(JSONArray data) {
        return new ResponseMsgJsonArray(ErrorCode.OK, "OK", data);
    }

    protected ResponseMsg responseData(Object data) {
        return new ResponseMsgData(ErrorCode.OK, "OK", data);
    }


}
